package com.flower.core_service.service.impl;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.flower.core_service.object.entity.AuthMenu;
import com.flower.core_service.mapper.AuthMenuMapper;
import com.flower.core_service.service.AuthMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单权限 服务实现类
 * </p>
 *
 * @author flower
 * @since 2022-03-29
 */
@Service
public class AuthMenuServiceImpl extends ServiceImpl<AuthMenuMapper, AuthMenu> implements AuthMenuService {

    /**
     * 递归查询子节点
     * @param root  根节点
     * @param all   所有节点
     * @return 根节点信息
     */
    private List<AuthMenu> getChildrens(AuthMenu root, List<AuthMenu> all) {
        List<AuthMenu> children = all.stream().filter(m -> {
            return Objects.equals(m.getPid(), root.getId());
        }).map(
                (m) -> {
                    m.setChildren(getChildrens(m, all));
                    return m;
                }
        ).collect(Collectors.toList());
        return children;
    }
    @Override
    public List<AuthMenu> getAllMenu() {
        List<AuthMenu>  menus=baseMapper.getAllMenu();
        List<AuthMenu> collect = menus.stream().filter(m -> m.getPid() .equals("0") ).map(
                (m) -> {
                    m.setChildren(getChildrens(m, menus));
                    return m;
                }
        ).collect(Collectors.toList());
        return collect;
    }

    @Override
    public void updateIcon(String id, String icon) {
        baseMapper.updateIcon(id, icon);
    }

    //递归删除所子菜单
    @Transactional
    @Override
    public void removeMenu(String id) {
        //查询当前节点的下一个子节点
        List<String> idList = baseMapper.selectIdListByPId(id);
        if(idList != null && idList.size() != 0)
        {
            for (String pid : idList) {
                removeMenu(pid);
            }
        }
        //删除当前节点
        baseMapper.deleteById(id);
    }
}
